package com.farm.web.restful;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.farm.authority.service.OrganizationServiceInter;
import com.farm.authority.service.OutuserServiceInter;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.page.ViewMode;
import com.farm.iproject.domain.Appdic;
import com.farm.iproject.domain.Appmodel;
import com.farm.iproject.domain.Dictype;
import com.farm.iproject.domain.Field;
import com.farm.iproject.domain.Pdocument;
import com.farm.iproject.domain.PopGroup;
import com.farm.iproject.domain.Project;
import com.farm.iproject.domain.Virtualfield;
import com.farm.iproject.service.AppdicServiceInter;
import com.farm.iproject.service.AppmodelServiceInter;
import com.farm.iproject.service.DictypeServiceInter;
import com.farm.iproject.service.FieldServiceInter;
import com.farm.iproject.service.PdocumentServiceInter;
import com.farm.iproject.service.PopgroupServiceInter;
import com.farm.iproject.service.PopgroupkeyServiceInter;
import com.farm.iproject.service.PopuserServiceInter;
import com.farm.iproject.service.ProjectServiceInter;
import com.farm.iproject.service.VirtualfieldServiceInter;
import com.farm.iproject.utils.JsonUtils;
import com.farm.parameter.service.ParameterServiceInter;
import com.farm.sfile.WdapFileServiceInter;
import com.farm.web.WebUtils;

/**
 * 组织机构、 [创建、查询、更新、删除] 用户、 [创建、查询、更新、删除] ---------------------------- 知识接口[查询]、
 * 分类接口[查询]、 问答接口[查询]、
 * 
 * @author wangdong
 *
 */
@RequestMapping("/api/index")
@Controller
public class IndexApiController extends WebUtils {
	private final static Logger log = Logger.getLogger(IndexApiController.class);
	@Resource
	private OrganizationServiceInter organizationServiceImpl;
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private OutuserServiceInter outUserServiceImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private ParameterServiceInter parameterServiceImpl;
	@Resource
	private AppmodelServiceInter appModelServiceImpl;
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private FieldServiceInter fieldServiceImpl;
	@Resource
	private PdocumentServiceInter pDocumentServiceImpl;
	@Resource
	private VirtualfieldServiceInter virtualFieldServiceImpl;
	@Resource
	private DictypeServiceInter dicTypeServiceImpl;
	@Resource
	private AppdicServiceInter appDicServiceImpl;
	@Resource
	private PopgroupServiceInter popGroupServiceImpl;
	@Resource
	private PopuserServiceInter popUserServiceImpl;
	@Resource
	private PopgroupkeyServiceInter popGroupKeyServiceImpl;

	/**
	 * 获得项目信息
	 * 
	 * @param key
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/project/get")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> projectGet(String key, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:项目查询");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(key)) {
				throw new RuntimeException("key is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(key);
			return ViewMode.getInstance().putAttr("DATA", project).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 项目注册索引域
	 * 
	 * @param projectKey
	 * @param name
	 * @param key
	 * @param storeis
	 * @param type
	 * @param sort
	 * @param texttype
	 * @param searchtype
	 * @param sortable
	 * @param boost
	 * @param maxlenght
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/regist/field")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> registField(String projectKey, String name, String key, String storeis,
			String type, int sort, String texttype, String searchtype, String sortable, int boost, int maxlenght,
			String secret, String operatorLoginname, String operatorPassword, HttpServletRequest request,
			HttpSession session) {
		try {
			log.info("restful API:注册索引域");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			if (project == null) {
				throw new RuntimeException("the project is not found:" + projectKey);
			}
			Field field = fieldServiceImpl.getFieldEntity(project.getId(), key);
			if (field == null) {
				field = new Field();
				field.setBoost(boost);
				field.setKeyid(key);
				field.setMaxlenght(maxlenght);
				field.setName(name);
				field.setType(type);
				field.setProjectid(project.getId());
				field.setSearchtype(searchtype);
				field.setSort(sort);
				field.setSortable(sortable);
				field.setStoreis(storeis);
				field.setTexttype(texttype);
				fieldServiceImpl.insertFieldEntity(field, userServiceImpl.getUserByLoginName(operatorLoginname));
			}
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 注册业务模型
	 * 
	 * @param projectKey
	 * @param name
	 * @param key
	 * @param sort
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/regist/appmodel")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> registAppmodel(String projectKey, String name, String key, int sort,
			String secret, String operatorLoginname, String operatorPassword, HttpServletRequest request,
			HttpSession session) {
		try {
			log.info("restful API:注册检索业务");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			Appmodel model = appModelServiceImpl.getAppmodel(project.getId(), key);
			if (model == null) {
				model = new Appmodel();
				model.setKeyid(key);
				model.setName(name);
				model.setProjectid(project.getId());
				model.setSort(sort);
				appModelServiceImpl.insertAppmodelEntity(model, userServiceImpl.getUserByLoginName(operatorLoginname));
			}
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 注册业务虚拟域
	 * 
	 * @param projectKey
	 * @param name
	 * @param key
	 * @param sort
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/regist/virtualfield")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> registVirtualField(String projectKey, String appKey, String name,
			String type, String formula, String secret, String operatorLoginname, String operatorPassword,
			HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:注册业务虚拟域");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			Appmodel model = appModelServiceImpl.getAppmodel(project.getId(), appKey);
			Virtualfield field = virtualFieldServiceImpl.getVirtualfield(project.getId(), appKey, type);
			if (field == null) {
				field = new Virtualfield();
				field.setAppmodelid(model.getId());
				field.setFormula(formula);
				field.setName(name);
				field.setType(type);
				virtualFieldServiceImpl.insertVirtualfieldEntity(field,
						userServiceImpl.getUserByLoginName(operatorLoginname));
			}
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 添加一个索引
	 * 
	 * @param projectid
	 * @param taskkey
	 * @param jsonstr
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> addindex(String projectid, String taskkey, String jsonstr, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:准备一个索引");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			Map<String, String> paras = JsonUtils.toMap(jsonstr);
			Pdocument document = pDocumentServiceImpl.submitDocument(projectid, taskkey, paras,
					ApiController.getUser(operatorLoginname));
			return ViewMode.getInstance().putAttr("DATA", document).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 执行索引
	 * 
	 * @param projectid
	 * @param taskkey
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/run")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> runindex(String projectid, String taskkey, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:批量处理索引");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			Thread t = new Thread(new Runnable() {
				public void run() {
					try {
						pDocumentServiceImpl.runIndex(taskkey, projectid);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
			t.start();
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 注册一级业务字典
	 * 
	 * @param projectKey
	 * @param fieldkey
	 * @param liketype
	 * @param abletype
	 * @param sumable
	 * @param name
	 * @param keyid
	 * @param sort
	 * @param appkeys           绑定字典到检索业务
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/regist/appdic")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> registAppdic(String projectKey, String fieldkey, String liketype,
			String abletype, String sumable, String name, String keyid, int sort, String appkeys, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:注册一级业务字典");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			Dictype type = dicTypeServiceImpl.getDictype(project.getId(), keyid);
			if (type == null) {
				type = new Dictype();
				type.setAbletype(abletype);
				type.setFieldkey(fieldkey);
				type.setProjectid(project.getId());
				type.setLiketype(liketype);
				type.setSumable(sumable);
				type.setKeyid(keyid);
				type.setName(name);
				type.setSort(sort);
				dicTypeServiceImpl.insertDictypeEntity(type, userServiceImpl.getUserByLoginName(operatorLoginname));
				for (String appkey : WebUtils.parseIds(appkeys)) {
					// 关联业务模型和检索字典
					Appmodel model = appModelServiceImpl.getAppmodel(project.getId(), appkey);
					if (model != null) {
						Appdic appdic = new Appdic();
						appdic.setAppid(model.getId());
						appdic.setDicid(type.getId());
						appDicServiceImpl.insertAppdicEntity(appdic,
								userServiceImpl.getUserByLoginName(operatorLoginname));
					}
				}
			}
			return ViewMode.getInstance().putAttr("DATA", type.getId()).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 清理业务字典子项
	 * 
	 * @param appdicid
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/clear/appdic")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> clearAppdic(String appdicid, String secret, String operatorLoginname,
			String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:清理业务字典子项");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(appdicid)) {
				throw new RuntimeException("appdicid is null!");
			}
			dicTypeServiceImpl.deleteAllSubDictype(appdicid);
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 添加业务字典子项
	 * 
	 * @param projectKey
	 * @param fieldkey
	 * @param liketype
	 * @param abletype
	 * @param sumable
	 * @param name
	 * @param sort
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/add/appdicnode")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> addAppdicnode(String projectKey, String appdicId, String key,
			String name, int sort, String parrentId, String secret, String operatorLoginname, String operatorPassword,
			HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:添加业务字典子项");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			Dictype type = new Dictype();
			type.setProjectid(project.getId());
			type.setKeyid(key);
			type.setName(name);
			type.setParentid(parrentId);
			type.setSort(sort);
			type.setSuperid(appdicId);
			dicTypeServiceImpl.insertDictypeEntity(type, userServiceImpl.getUserByLoginName(operatorLoginname));
			return ViewMode.getInstance().putAttr("DATA", type.getId()).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 删除权限组
	 * 
	 * @param projectKey
	 * @param groupname
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/del/popgroups")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> delPopgroups(String projectKey, String groupname, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:删除权限组");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			popGroupServiceImpl.deletePopgourps(project.getId(), groupname,
					userServiceImpl.getUserByLoginName(operatorLoginname));
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 初始化一个权限组
	 * 
	 * @param projectKey
	 * @param groupname
	 * @param note
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/init/popgroup")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> initPopgroup(String projectKey, String groupname, String note,
			String secret, String operatorLoginname, String operatorPassword, HttpServletRequest request,
			HttpSession session) {
		try {
			log.info("restful API:初始化权限组");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			if (StringUtils.isBlank(groupname)) {
				throw new RuntimeException("groupname is null!");
			}
			PopGroup group = popGroupServiceImpl.getPopgroupByName(project.getId(), groupname);
			if (group == null) {
				group = new PopGroup();
				group.setGroupname(groupname);
				group.setPcontent(note);
				group.setProjectid(project.getId());
				group.setPstate("1");
				popGroupServiceImpl.insertPopgroupEntity(group, userServiceImpl.getUserByLoginName(operatorLoginname));
			}
			return ViewMode.getInstance().putAttr("DATA", group.getId()).returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 添加权限组用户
	 * 
	 * @param gourpid
	 * @param key
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/add/popuser")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> addPopuser(String gourpid, String key, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:添加权限组用户");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(gourpid)) {
				throw new RuntimeException("gourpid is null!");
			}
			if (popGroupServiceImpl.getPopgroupEntity(gourpid) == null) {
				throw new RuntimeException("gourpid is not exist:" + gourpid);
			}
			popUserServiceImpl.addGroupUser(gourpid, key);
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 添加权限组权限
	 * 
	 * @param gourpid
	 * @param key
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/add/popkey")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> addPopkey(String groupid, String keys, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:添加权限组权限");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(groupid)) {
				throw new RuntimeException("gourpid is null!");
			}
			if (popGroupServiceImpl.getPopgroupEntity(groupid) == null) {
				throw new RuntimeException("gourpid is not exist:" + groupid);
			}
			popGroupKeyServiceImpl.addGroupKey(groupid, parseIds(keys));
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 删除一条索引
	 * 
	 * @param projectKey
	 * @param appid             索引id
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> del(String projectKey, String appid, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:删除一条索引");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			pDocumentServiceImpl.delDocument(project.getId(), appid,
					userServiceImpl.getUserByLoginName(operatorLoginname), true);
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}

	/**
	 * 删除全部索引
	 * 
	 * @param projectKey
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/removeall")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> clear(String projectKey, String appkeyid, String secret,
			String operatorLoginname, String operatorPassword, HttpServletRequest request, HttpSession session) {
		try {
			log.info("restful API:删除全部索引");
			ApiController.checkSecret(secret, request);
			ApiController.checkAuth(operatorLoginname, operatorPassword);
			if (StringUtils.isBlank(projectKey)) {
				throw new RuntimeException("projectKey is null!");
			}
			Project project = projectServiceImpl.getProjectByKey(projectKey);
			pDocumentServiceImpl.deleteAllIndex(project.getId(), appkeyid,
					userServiceImpl.getUserByLoginName(operatorLoginname));
			return ViewMode.getInstance().returnJsonMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnJsonMode();
		}
	}
}
